# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from typing import Optional
from python.mypackage import TreeNode


class Solution:
    
    """
    方法： invertTree
    Args: root (Optional[TreeNode]): 二叉树的根节点
    Returns: Optional[TreeNode]: 反转后的二叉树根节点
    Time: O(n)
    Space: O(h)  # h 是树的高度
    """
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None: return None
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root
        
    """
    方法： invertTree1
    Args: root (Optional[TreeNode]): 二叉树的根节点
    Returns: Optional[TreeNode]: 反转后的二叉树根节点
    Time: O(n)
    Space: O(n)  # 使用队列存储节点
    """
    def invertTree1(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None: return None
        queue = [root]
        while queue:
            tmp = queue.pop(0)
            tmp.left, tmp.right = tmp.right, tmp.left
            if tmp.left:
                queue.append(tmp.left)
            if tmp.right:
                queue.append(tmp.right)
        return root